<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>主播开播页面</title>
  <style>
    body, html {
      margin: 0; padding: 0;
      height: 100%; width: 100%;
      background: #000;
      font-family: Arial, sans-serif;
      color: #fff;
    }
    .container {
      position: relative;
      width: 100%; height: 100%;
      overflow: hidden;
    }
    video {
      width: 100%; height: 100%;
      object-fit: cover;
      background: #000;
    }
	#publishUrl{
		display:none
	}
    /* 顶部状态栏 */
    .status-bar {
      position: absolute;
      top: 10px; left: 50%;
      transform: translateX(-50%);
      background: rgba(0,0,0,0.6);
      padding: 6px 12px;
      border-radius: 20px;
      font-size: 14px;
    }
    /* 底部控制栏 */
    .control-bar {
      position: absolute;
      bottom: 0; left: 0; right: 0;
      background: rgba(0,0,0,0.6);
      padding: 10px;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      justify-content: center;
    }
    .control-bar input {
      flex: 1;
      padding: 8px 10px;
      border-radius: 6px;
      border: none;
      font-size: 14px;
    }
    .btn {
      padding: 8px 14px;
      border-radius: 6px;
      border: none;
      background: #4f8cff;
      color: #fff;
      font-size: 14px;
      cursor: pointer;
	  width: 45%;
    }
    .btn.danger { background: #ef4444; }
    .toggle-group {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 14px;
    }
    
    /* 新增海报相关样式 */
    .share-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background: rgba(0,0,0,0.6);
      color: #fff;
      border: none;
      border-radius: 20px;
      padding: 6px 12px;
      font-size: 14px;
      cursor: pointer;
      z-index: 10;
    }
    
    .poster-modal {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.8);
      z-index: 100;
      justify-content: center;
      align-items: center;
    }
    
    .poster-content {
      background: #222;
      padding: 20px;
      border-radius: 15px;
      text-align: center;
      color: #fff;
      max-width: 90%;
      box-shadow: 0 5px 25px rgba(0,0,0,0.5);
    }
    
    .poster-content h3 {
      margin-top: 0;
      color: #4f8cff;
      font-size: 1.5rem;
      margin-bottom: 15px;
    }
    
    #posterCanvas {
      max-width: 100%;
      margin: 10px 0;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0,0,0,0.3);
    }
    
    .poster-actions {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-top: 15px;
    }
    
    .poster-actions button {
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-weight: bold;
      transition: all 0.3s;
    }
    
    .save-btn {
      background: #4f8cff;
      color: white;
    }
    
    .save-btn:hover {
      background: #3a7bff;
    }
    
    .close-btn {
      background: #666;
      color: #fff;
    }
    
    .close-btn:hover {
      background: #555;
    }
    
    .invite-code {
      font-size: 1.2rem;
      font-weight: bold;
      color: #ffcc00;
      margin: 10px 0;
      padding: 8px;
      background: rgba(0,0,0,0.3);
      border-radius: 5px;
      letter-spacing: 2px;
    }
  </style>
</head>
<body>
<div class="container">
  <!-- 本地视频预览 -->
  <video id="localVideo" autoplay muted playsinline></video>

  <!-- 状态栏 -->
  <div class="status-bar" id="pushStatus">未推流</div>
  
  <!-- 分享按钮 -->
  <button class="share-btn" id="shareBtn">生成海报</button>

  <!-- 控制栏 -->
  <div class="control-bar">
    <input id="publishUrl" type="text" value="http://localhost:1985/rtc/v1/publish/" placeholder="推流地址 (https://your-srs/rtc/v1/publish/)">
    <button id="btnStartPush" class="btn">开始推流</button>
    <button id="btnStopPush" class="btn danger" disabled>停止推流</button>
    <div class="toggle-group">
      <label><input type="checkbox" id="toggleVideo" checked> 视频</label>
      <label><input type="checkbox" id="toggleAudio" checked> 音频</label>
    </div>
  </div>
</div>

<!-- 海报模态框 -->
<div class="poster-modal" id="posterModal">
  <div class="poster-content">
    <h3>直播间分享海报</h3>
    <canvas id="posterCanvas" width="300" height="450"></canvas>
    <div class="invite-code" id="inviteCodeDisplay"></div>
    <div class="poster-actions">
      <button class="save-btn" id="savePosterBtn">保存海报</button>
      <button class="close-btn" id="closePosterBtn">关闭</button>
    </div>
  </div>
</div>

<script>
const $=id=>document.getElementById(id);
let pc, localStream;

function setPushStatus(text, active=false){
  $("pushStatus").textContent=text;
  $("pushStatus").style.color= active? "#22c55e" : "#fff";
}

// 生成随机邀请码
function generateInviteCode() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let code = '';
  for (let i = 0; i < 6; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
}

// 加载图片
function loadImage(src) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "Anonymous";
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = src;
  });
}

// 生成海报
async function generatePoster() {
  const canvas = $("posterCanvas");
  const ctx = canvas.getContext("2d");
  const inviteCode = generateInviteCode();
  
  // 显示邀请码
  $("inviteCodeDisplay").textContent = `邀请码: ${inviteCode}`;
  
  try {
    // 清空画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 加载背景图（使用随机渐变背景代替外部图片，避免跨域问题）
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
    gradient.addColorStop(0, '#1a2a6c');
    gradient.addColorStop(0.5, '#b21f1f');
    gradient.addColorStop(1, '#fdbb2d');
    
    // 绘制背景
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制装饰性元素
    ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
    for (let i = 0; i < 50; i++) {
      const x = Math.random() * canvas.width;
      const y = Math.random() * canvas.height;
      const size = Math.random() * 3;
      ctx.beginPath();
      ctx.arc(x, y, size, 0, Math.PI * 2);
      ctx.fill();
    }
    
    // 绘制内容区域背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
    ctx.beginPath();
    ctx.roundRect(20, 20, canvas.width - 40, canvas.height - 40, 15);
    ctx.fill();
    
    // 绘制标题
    ctx.fillStyle = '#fff';
    ctx.font = "bold 24px Arial";
    ctx.textAlign = "center";
    ctx.fillText("直播间邀请", canvas.width / 2, 60);
    
    // 绘制二维码区域背景
    ctx.fillStyle = "#fff";
    ctx.beginPath();
    ctx.roundRect(50, 80, 200, 200, 10);
    ctx.fill();
    
    // 绘制二维码图案（模拟）
    ctx.fillStyle = "#000";
    
    // 绘制二维码定位标记
    ctx.fillRect(65, 95, 40, 40);
    ctx.fillRect(195, 95, 40, 40);
    ctx.fillRect(65, 225, 40, 40);
    
    ctx.clearRect(70, 100, 30, 30);
    ctx.clearRect(200, 100, 30, 30);
    ctx.clearRect(70, 230, 30, 30);
    
    ctx.fillRect(78, 108, 14, 14);
    ctx.fillRect(208, 108, 14, 14);
    ctx.fillRect(78, 238, 14, 14);
    
    // 绘制二维码内容
    ctx.font = "14px Arial";
    ctx.fillText("扫描二维码", canvas.width / 2, 310);
    ctx.fillText("加入直播间", canvas.width / 2, 330);
    
    // 绘制分隔线
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    ctx.beginPath();
    ctx.moveTo(50, 350);
    ctx.lineTo(250, 350);
    ctx.stroke();
    
    // 绘制邀请码
    ctx.font = "bold 22px Arial";
    ctx.fillStyle = '#ffcc00';
    ctx.fillText(`邀请码: ${inviteCode}`, canvas.width / 2, 390);
    
    // 绘制提示文字
    ctx.font = "14px Arial";
    ctx.fillStyle = '#ccc';
    ctx.fillText("输入邀请码即可加入", canvas.width / 2, 420);
    
  } catch (e) {
    console.error("生成海报失败:", e);
    alert("生成海报失败，请重试");
  }
  
  // 显示模态框
  $("posterModal").style.display = "flex";
}

// 保存海报
function savePoster() {
  const canvas = $("posterCanvas");
  const link = document.createElement("a");
  link.download = "直播间海报.png";
  link.href = canvas.toDataURL("image/png");
  link.click();
}

// 开始推流
async function startPush(){
  const url=$("publishUrl").value.trim();
  if(!url) return alert("请输入推流地址");

  try{
    // 获取本地摄像头/麦克风
    localStream=await navigator.mediaDevices.getUserMedia({
      video:$("toggleVideo").checked,
      audio:$("toggleAudio").checked
    });
    $("localVideo").srcObject=localStream;

    // 创建 WebRTC 连接
    const pcConfig = {bundlePolicy: "max-bundle" };
    pc = new RTCPeerConnection(pcConfig);
    localStream.getTracks().forEach(track=>{
		pc.addTrack(track,localStream)
	});

    const offer = await pc.createOffer({
	  offerToReceiveAudio: false,
	  offerToReceiveVideo: false
    });
    await pc.setLocalDescription(offer);
	
	
	
	// 通过 SRS API 交换 SDP
      const body = {
        url,
        sdp: offer.sdp,
        streamurl: "webrtc://localhost/live/test",
        // 可选参数：客户端标识 / IP
        tid: Math.random().toString(36).slice(2),
        clientip: null
      };
      const resp = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body)
      });
	

    // 发送 SDP 到 SRS
    // const resp=await fetch(url,{
    //   method:"POST",
    //   body:JSON.stringify({sdp:offer.sdp,type:offer.type}),
    //   headers:{"Content-Type":"application/json"}
    // });
    const data=await resp.json();
    await pc.setRemoteDescription({ type: "answer", sdp: data.sdp });

    setPushStatus("推流中...",true);
    $("btnStartPush").disabled=true;
    $("btnStopPush").disabled=false;
  }catch(e){
    console.error(e);
    alert("推流失败:"+e.message);
    setPushStatus("推流失败");
  }
}

// 停止推流
function stopPush(){
  if(pc){pc.close(); pc=null;}
  if(localStream){
    localStream.getTracks().forEach(t=>t.stop());
    localStream=null;
  }
  $("localVideo").srcObject=null;
  setPushStatus("未推流");
  $("btnStartPush").disabled=false;
  $("btnStopPush").disabled=true;
}

// 开关音视频
$("toggleVideo").onchange=()=>{
  if(localStream) localStream.getVideoTracks().forEach(t=>t.enabled=$("toggleVideo").checked);
};
$("toggleAudio").onchange=()=>{
  if(localStream) localStream.getAudioTracks().forEach(t=>t.enabled=$("toggleAudio").checked);
};

$("btnStartPush").onclick=startPush;
$("btnStopPush").onclick=stopPush;

// 海报相关事件
$("shareBtn").onclick = generatePoster;
$("savePosterBtn").onclick = savePoster;
$("closePosterBtn").onclick = () => {
  $("posterModal").style.display = "none";
};

// 初始化
window.onload = function() {
  // 预加载
  console.log("页面加载完成");
};
</script>
</body>
</html>